﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CloudShot.Utils
{
	internal sealed class HotkeyListener
	{
		private readonly GlobalHotListener _hotkeyListener;
		private readonly Dictionary<string, KeyValuePair<Hotkey, EventHandler>> _registeredHotkeys;

		public HotkeyListener(Form parent)
		{
			_hotkeyListener = new GlobalHotListener(parent);
			_registeredHotkeys = new Dictionary<string, KeyValuePair<Hotkey, EventHandler>>();

			parent.HandleDestroyed += (sender, args) => UnregisterAll();
		}

		public bool RegisterHotkey(string name, string hotkeyShortcut, EventHandler callbackAction)
		{
			Hotkey hotkey;

			if (!Hotkey.TryParse(hotkeyShortcut, out hotkey))
				return false;
				//throw new ArgumentException("Invalid hotkey shortcut", "hotkeyShortcut");

			if (!_hotkeyListener.Add(hotkey))
				return false;

			_registeredHotkeys.Add(name, new KeyValuePair<Hotkey, EventHandler>(hotkey, callbackAction));
			hotkey.HotkeyPressed += callbackAction;
			return true;
		}

		public bool UnregisterHotkey(string name)
		{
			KeyValuePair<Hotkey, EventHandler> hotkey;

			if (!_registeredHotkeys.TryGetValue(name, out hotkey))
				return false;

			hotkey.Key.HotkeyPressed -= hotkey.Value;
			_hotkeyListener.Remove(hotkey.Key);
			_registeredHotkeys.Remove(name);

			return true;
		}

		public void UnregisterAll()
		{
			foreach (KeyValuePair<Hotkey, EventHandler> hotkey in _registeredHotkeys.Values)
			{
				hotkey.Key.HotkeyPressed -= hotkey.Value;
				_hotkeyListener.Remove(hotkey.Key);
			}

			_registeredHotkeys.Clear();
		}
	}
}